//
//  UIImage + Extension.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/3/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit


extension UIImage {
    
    class func snapshotWithBlurEffectFromViewHierarchy(view: UIView) -> UIImage {
        // 开启一个图形上下文
        UIGraphicsBeginImageContextWithOptions(kScreenBounds.size, true, 0)
        // 将 view hierarchy 绘制到图形上下文
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: false)
        // 从图形上下文中获取图片
        var snapshot = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图形上下文
        UIGraphicsEndImageContext()
        
        snapshot = snapshot.applyLightEffect()
        
        return snapshot
        
    }
    
    ///  拉伸图片
    ///
    ///  - returns: 拉伸后的图片
    func slicedImage() -> UIImage {
        let insetH = self.size.height * 0.5
        let insetW = self.size.width * 0.5
        let sImg = self.resizableImageWithCapInsets(UIEdgeInsets(top: insetH, left: insetW, bottom: insetH, right: insetW), resizingMode: UIImageResizingMode.Stretch)
        return sImg
    }
    
    ///  等比例缩放
    ///
    ///  - parameter targetSize: 目标size，边长以较长的为准
    ///
    ///  - returns: 缩放后的图像
    func scaledImage(targetSize: CGSize) -> UIImage {
        
        
        // 以较长的边为准
        let targetSideLength = max(targetSize.width, targetSize.height)
        
        // 如果原始边长就过小，则直接返回
        if targetSideLength > max(self.size.width, self.size.height) {
            return self
        }
        
        let longer = self.size.width > self.size.height
        
        
        
        let size: CGSize
        if longer { // 宽 > 高，固定边长为高
            size = CGSizeMake((targetSideLength / self.size.height) * self.size.width, targetSideLength)
        } else { // 宽 < 高，固定边长为宽
            size = CGSizeMake(targetSideLength, (targetSideLength / self.size.width) * self.size.height)
        }
        
        // 开启一个特定大小的图形上下文
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        // 绘制
        self.drawInRect(CGRectMake(0, 0, size.width, size.height))
        // 获取绘制好的图片
        let img = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图形上下文
        UIGraphicsEndImageContext()
        // 返回图片
        return img
    }
}